/**

 @Name：layuiAdmin 用户管理 管理员管理 角色管理
 @Author：star1029
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */


layui.define(['table', 'form', 'dtree', 'xmSelect','aut'], function (exports) {
  var $ = layui.$,
    admin = layui.admin,
    view = layui.view,
    table = layui.table,
    form = layui.form,
    dtree = layui.dtree,
    setter = layui.setter,
    xmSelect = layui.xmSelect,
    aut = layui.aut;

  var ok = setter.response.statusCode.ok;
  var fail = setter.response.statusCode.fail;
  var error = setter.response.statusCode.error;
  var forbidden = setter.response.statusCode.forbidden;

  //管理员管理
  table.render({
    elem: '#LAY-user-back-manage',
    url: '/mrc/user',
    loading: true,
    headers: {
      access_token: layui.data('layuiAdmin').access_token
    },
    page: true,
    minWidth: 150,
    cols: [
      [{
        field: 'userId',
        title: 'ID',
        sort: true
      }, {
        field: 'userName',
        title: '登录名'
      }, {
        field: 'roleName',
        title: '角色'
      }, {
        field: 'isLock',
        title: '账号状态',
        templet: '#buttonTpl',
        align: 'center'
      }, {
        title: '操作',
        width: 150,
        align: 'center',
        fixed: 'right',
        toolbar: '#table-useradmin-user'
      }]
    ]
  });

  aut.data([
    {id:"LAY-user-back-search",alias:"user::get"},
    {id:"LAY-user-back-add",alias:"user::add"},
  ])

  //监听工具条
  table.on('tool(LAY-user-back-manage)', function (obj) {
    var data = obj.data;
    if (obj.event === 'del') {
      layer.confirm('确定删除此管理员？', function (index) {
        admin.req({
          type: "delete",
          url: "/mrc/user/" + data.userId,
          success: function (res) {
            if (res.code == ok) {
              layer.msg("删除成功！", {
                icon: 1
              })
            } else if (res.code == forbidden) {
              layer.msg(res.msg, {
                icon: 2
              })
            } else if (res.code == fail) {
              layer.msg("删除失败！请重试！", {
                icon: 2
              })
            }
            user_table_reload();
          },
          error: function () {
            layer.msg("系统出错！", {
              icon: 2
            })
          }
        });
        layer.close(index);
      });

    } else if (obj.event === 'edit') {
      admin.popup({
        title: '编辑管理员',
        area: ['420px', '450px'],
        id: 'LAY-popup-user-add',
        success: function (layero, index) {
          view(this.id).render('user/administrators/adminform', data).done(function () {
            form.render(null, 'layuiadmin-form-admin');

            var xm = xmSelect.render({
              el: '#LAY-user-admin-list-form-roleSelect',
              filterable: true,
              paging: true,
              radio: true,
              clickClose: true,
              pageEmptyShow: false,
              layVerify: 'required',
              data: []
            })

            admin.req({
              type: "get",
              url: "/mrc/public/roleSelect",
              success: function (res) {
                var b = false;
                data.roleName == "管理员" ? b = true : b = false;

                if (res.code == 200) {
                  res.data.forEach(function (a) {
                    try {
                      if (a.name == "管理员") {
                        a.disabled = true;
                      }
                      if (a.name == data.roleName) {
                        a.selected = true;
                        throw new Error("EndIterative");
                      }
                    } catch (e) {
                      if (e.message != "EndIterative") throw e;
                    }
                  })
                  if (b) {
                    xm.update({
                      data: res.data,
                      autoRow: true,
                      disabled: true
                    })
                  } else {
                    xm.update({
                      data: res.data,
                      autoRow: true
                    })
                  }

                }
              },
              error: function () {
                xm.update({
                  data: [],
                  autoRow: true
                })
              }
            })

            //监听提交
            form.on('submit(LAY-user-back-submit)', function (data) {
              var field = data.field; //获取提交的字段
              delete field.select;
              var selectArr = xm.getValue('valueStr');
              field.roleId = selectArr;
              // console.log(field);
              admin.req({
                type: "put",
                url: "/mrc/user",
                data: JSON.stringify(field),
                dataType: "json",
                contentType: "application/json",
                success: function (res) {
                  if (res.code == ok) {
                    layer.msg("修改成功", {
                      icon: 1
                    })
                  } else if (res.code == forbidden) {
                    layer.msg(res.msg, {
                      icon: 2
                    })
                  } else {
                    layer.msg("系统出错，请联系开发人员", {
                      icon: 0
                    })
                  }
                }
              });

              layer.close(index); //执行关闭 
            });
          });
        },
        end: function () {
          user_table_reload();
        }
      });
    }
  });

  function user_table_reload() {

    var index = layer.load();
    table.reload('LAY-user-back-manage', {
      url: '/mrc/user'
    });
    layer.close(index);

  }



  //角色管理
  table.render({
    elem: '#LAY-user-back-role',
    url: '/mrc/role',
    minWidth: 150,
    page: true,
    loading: true,
    headers: {
      access_token: layui.data('layuiAdmin').access_token
    },
    cols: [
      [{
        field: 'roleId',
        title: 'ID',
        sort: true
      }, {
        field: 'roleName',
        title: '角色名'
      }, {
        field: 'description',
        title: '具体描述'
      }, {
        title: '操作',
        width: 150,
        align: 'center',
        fixed: 'right',
        toolbar: '#table-useradmin-role'
      }]
    ]
  });

  aut.data([
    {id:"LAY-user-admin-role-search",alias:"role::get"},
  ])

  //监听工具条
  table.on('tool(LAY-user-back-role)', function (obj) {
    var data = obj.data;
    if (obj.event === 'del') {
      layer.confirm('确定删除此角色？', function (index) {
        var load = layer.load();
        admin.req({
          type: "delete",
          url: "/mrc/role/" + data.roleId,
          success: function (res) {
            layer.close(load);
            if (res.code == ok) {
              layer.msg("删除角色成功！", {
                icon: 1
              })
            } else if (res.code == fail) {
              layer.msg("删除角色失败！" + res.msg, {
                icon: 1
              })
            } else if (res.code == forbidden) {
              layer.msg(res.msg, {
                icon: 2
              })
            } else if (res.code == error) {
              layer.msg("系统错误！请联系开发商", {
                icon: 0
              })
            }
            role_table_reload();
          },
          error: function () {
            layer.close(load);
          }
        })

        layer.close(index);
      });
    } else if (obj.event === 'edit') {
      admin.popup({
        title: '编辑角色',
        area: ['40%', '70%'],
        id: 'LAY-popup-user-add',
        success: function (layero, index) {
          view(this.id).render('user/administrators/roleform', data).done(function () {
            form.render(null, 'layuiadmin-form-role');

            var Dtree = tree(data.roleId);

            //监听提交
            form.on('submit(LAY-user-role-submit)', function (data) {
              var load = layer.load();

              var field = data.field;
              var params = dtree.getCheckbarNodesParam("demoTree");
              var list = [];
              params.forEach(function (item) {
                if (item.level == 3) {
                  list.push(item.nodeId);
                }
              })
              if (list.length == 0) {
                layer.msg("请选择权限！", {
                  icon: 0
                })
                layer.close(load);
                return false;
              }
              field.list = list;

              admin.req({
                type: "put",
                url: "/mrc/role",
                data: JSON.stringify(field),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                  layer.close(load);
                  if (res.code == ok) {
                    layer.msg("修改角色成功！重新登录生效！", {
                      icon: 1
                    })
                  } else if (res.code == fail) {
                    layer.msg("新增角色失败！", {
                      icon: 1
                    })
                  } else if (res.code == forbidden) {
                    layer.msg(res.msg, {
                      icon: 2
                    })
                  } else {
                    layer.msg("系统错误，请联系开发商！", {
                      icon: 2
                    })
                  }
                  window.location.reload();
                },
                error: function () {
                  layer.msg("系统错误！请联系开发商！", {
                    icon: 0
                  })
                  layer.close(load);
                }
              });

              layer.close(index); //执行关闭 
            });
          });
        },
        end: function () {
          role_table_reload();
        }
      });
    }
  });

  var active = {
    add: function () {
      admin.popup({
        title: '添加新角色',
        area: ['40%', '70%'],
        id: 'LAY-popup-user-add',
        success: function (layero, index) {
          view(this.id).render('user/administrators/roleform').done(function () {
            form.render(null, 'layuiadmin-form-role');

            var Dtree = tree(0);

            form.on('submit(LAY-user-role-submit)', function (data) {
              var load = layer.load();

              var field = data.field;
              var params = dtree.getCheckbarNodesParam("demoTree");
              var list = [];
              params.forEach(function (item) {
                if (item.level == 3) {
                  list.push(item.nodeId);
                }
              })
              if (list.length == 0) {
                layer.msg("请选择权限！", {
                  icon: 0
                })
                layer.close(load);
                return false;
              }
              field.list = list;

              admin.req({
                type: "post",
                url: "/mrc/role",
                data: JSON.stringify(field),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                  layer.close(load);
                  if (res.code == ok) {
                    layer.msg("新增角色成功！", {
                      icon: 1
                    })
                  } else if (res.code == fail) {
                    layer.msg("新增角色失败！", {
                      icon: 1
                    })
                  } else if (res.code == forbidden) {
                    layer.msg(res.msg, {
                      icon: 2
                    })
                  } else {
                    layer.msg("系统错误，请联系开发商！", {
                      icon: 2
                    })
                  }
                },
                error: function () {
                  layer.msg("系统错误！请联系开发商！", {
                    icon: 0
                  })
                  layer.close(load);
                }
              });


              layer.close(index);
            });
          });
        },
        end: function () {
          role_table_reload();
        }
      });
    }
  }

  function tree(d) {

    var DemoTree = dtree.render({
      elem: "#demoTree",
      headers: {
        access_token: layui.data('layuiAdmin').access_token
      },
      scroll: "#toolbarDiv",
      url: "/mrc/rbac/tree?roleId=" + d,
      dataStyle: "layuiStyle",
      checkbar: true,
      checkbarType: "all",
      line: true,
      icon: "2",
      initLevel: 2,
      method: "GET",
      response: {
        message: "msg",
        statusCode: 200
      },
      done: function (res, $ul, first) {
        if (first) {
          dtree.chooseDataInit("demoTree", "1259749679349239808"); // 初始化选中
        }
        DemoTree.setDisabledNodes("1259749679349239808");
      }
    });

    return DemoTree;
  }

  function role_table_reload() {
    var index = layer.load();
    table.reload('LAY-user-back-role', {
      url: '/mrc/role'
    });
    layer.close(index);
  }

  $('.layui-btn.layuiadmin-btn-role').on('click', function () {
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });

  exports('useradmin', {})
});